import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/assets/images/user.png'
import { blobValidate } from '@/utils/ruoyi'
import axios from 'axios'
const baseURL = import.meta.env.VITE_APP_BASE_API

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      name: '',
      avatar: '',
      roles: [],
      permissions: []
    }),
    actions: {
      // 登录
      login(userInfo) {
        const username = userInfo.username.trim()
        const password = userInfo.password
        const code = userInfo.code
        const uuid = userInfo.uuid
        const orgId = userInfo.orgId
        const orgName = userInfo.orgName
        return new Promise((resolve, reject) => {
          login(username, password, code, uuid, orgId,orgName).then(res => {
            let data = res.data
            setToken(data.access_token)
            this.token = data.access_token
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            const user = res.user
            const avatar = user.avatar ? user.avatar : defAva;

            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.roles
              this.permissions = res.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.name = user.userName
            this.avatar = avatar;
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          logout(this.token).then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            removeToken()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      //根据id显示图片流
      getPicStreamById(id) {
        return new Promise((resolve,reject) => {
          var url = baseURL + "/system/file/download/" + id;
          axios({
            method: 'get',
            url: url,
            responseType: 'blob',
            headers: { 'Authorization': 'Bearer ' + getToken() }
          }).then(async (res) => {
            const isLogin = await blobValidate(res.data);
            if (isLogin) {
              const blob = new Blob([res.data])
              resolve(URL.createObjectURL(blob));
            } else {
              reject('未找到图片');
            }
          })
        });
      },
    }
  })

export default useUserStore
